package cn.edu.eight.food.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/upload")
public class uploadController {

    @RequestMapping("/imgUpload")
    @ResponseBody
    public Map<String, Object> upload(HttpServletRequest request,
                                      @RequestParam("file") MultipartFile file) throws IOException {
        Map<String, Object> res = new HashMap<>();
        System.out.println(file.getOriginalFilename());
        //如果文件内容不为空，则写入上传路径
        if (!file.isEmpty()) {
            System.out.println(file.getOriginalFilename());
            //上传文件路径
            // 上传文件名
            String fileName = file.getOriginalFilename();
            String paths = System.getProperty("user.dir") + File.separator + "src" + File.separator + "main" + File.separator + "resources" + File.separator + "static" + File.separator + "images" + File.separator;//保存的路径
            File filepath = new File(paths, fileName);
            System.out.println(filepath);
            //判断路径是否存在，没有就创建一个
            if (!filepath.getParentFile().exists()) {
                filepath.getParentFile().mkdirs();
            }
            //将上传文件保存到一个目标文档中
            File file1 = new File(paths + File.separator + fileName);
            file.transferTo(file1);
            //返回的是一个url对象
            res.put("code", 200);
            return res;
        } else {
            res.put("error","上传错误");
            return res;
        }
    }
}
